﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using mitasoft.Web.DAL.Model;
using Twitterizer;
using mitasoft.Web.Business.Interfaces;
using System.Net;
using System.Xml.Linq;

namespace mitasoft.Web.Business
{

    public class SocialBusiness : ISocialBusiness
    {
        /// <summary>
        /// Get twitter messages
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public IEnumerable<TwitterMessage> GetTwitterMessages(int count)
        {

            var timeline = TwitterTimeline.UserTimeline(new UserTimelineOptions() { ScreenName = "mita_soft" });
            var tweets = timeline.ResponseObject.Take(count);

            return tweets.Select(t => new TwitterMessage
            {
                Message = t.Text,
                //ShortMessage = t.Text.Length > 40 ? t.Text.Substring(0, 40) + "..." : t.Text,
                ShortMessage = t.Text,
                Date = t.CreatedDate
            });

        }

        /// <summary>
        /// Get blog posts
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        public IEnumerable<BlogPost> GetBlogPosts(int count)
        {
            WebClient client = new WebClient();
            byte[] data = client.DownloadData("http://mitasoft.wordpress.com/feed/");

            string feed = Encoding.ASCII.GetString(data, 0, data.Count());
            XDocument feedDoc = XDocument.Parse(feed);

            var blogPost = feedDoc.Root.Element("channel").Elements()
                .Where(e => e.Name == "item")
                .Take(count)
                .ToList();

            List<BlogPost> blogPostsList = new List<BlogPost>();
            foreach (var post in blogPost)
            {
                blogPostsList.Add(new BlogPost
                {
                    Date = DateTime.Parse(post.Element("pubDate").Value),
                    Title = post.Element("title").Value.Length < 32 ? post.Element("title").Value 
                    : post.Element("title").Value.Substring(0, 32) + "...",
                    
                    URL = post.Element("link").Value
                });
            }

            return blogPostsList;
        }
    }
}
